package logger

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"time"
)

var logger *zap.SugaredLogger
var loggerConsole *zap.SugaredLogger

func init() {
	encoderConfig := zap.NewProductionEncoderConfig()
	//encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
	encoderConfig.EncodeTime = parseTime("[2006-01-02 15:04:05.000]")
	lumberjackLogger := &lumberjack.Logger{
		Filename:   "./logs/aiSpeaker.log", // -- 日志文件名
		MaxSize:    10,                     // -- 最大日志数 M为单位!!!
		MaxAge:     15,                     // -- 最大存在天数
		MaxBackups: 500,                    // -- 最大备份数量
		Compress:   true,                   // --是否压缩
		LocalTime:  true,
	}
	core := zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.AddSync(lumberjackLogger), zap.DebugLevel)
	logger = zap.New(core).Sugar()

	coreConsole := zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.AddSync(os.Stdout), zap.DebugLevel)
	loggerConsole = zap.New(coreConsole).Sugar()
}

func parseTime(layout string) zapcore.TimeEncoder {
	return func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
		type appendTimeEncoder interface {
			AppendTimeLayout(time.Time, string)
		}
		if enc, ok := enc.(appendTimeEncoder); ok {
			enc.AppendTimeLayout(t, layout)
			return
		}
		enc.AppendString(t.Format(layout))
	}
}

func Infof(template string, args ...interface{}) {
	logger.Infof(template, args...)
	loggerConsole.Infof(template, args...)

}

func Info(args ...interface{}) {
	logger.Info(args...)
	loggerConsole.Info(args...)
}

func Error(args ...interface{}) {
	logger.Error(args...)
	loggerConsole.Error(args...)
}

func Errorf(template string, args ...interface{}) {
	logger.Errorf(template, args...)
	loggerConsole.Errorf(template, args...)
}
